package com.qc.common.web;

import org.apache.tiles.Attribute;
import org.apache.tiles.AttributeContext;
import org.apache.tiles.preparer.ViewPreparer;
import org.apache.tiles.request.Request;
import org.apache.tiles.request.servlet.ServletRequest;

public class PJAXViewPreparer implements ViewPreparer {
	@Override
	public void execute(Request request, AttributeContext attributeContext) {
		boolean doPjax = false;
		if(request.getHeader().containsKey("x-pjax") ) {
			doPjax = true;
		}
		if(request instanceof ServletRequest) {
			ServletRequest sr = (ServletRequest) request;
			if(sr.getRequestScope()!=null && sr.getRequestScope().get("redirect")!=null) {
				sr.getResponseHeaders().setValue("X-PJAX-URL", (String) sr.getRequestScope().get("redirect"));
			}
		}
		if(doPjax) {
			Attribute template = attributeContext.getTemplateAttribute();
			String templatePath = (String) template.getValue();
			templatePath = templatePath.replace("default", "pjax");
			template.setValue(templatePath);
			attributeContext.setTemplateAttribute(template);
		}

	}
}